package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.canton.exhibitor.BaseCantonFairExhibitor;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import com.shlh.saas.service.canton.exhibitor.CantonFairExhibitorService;
import com.shlh.saas.service.ExportRecordService;
import com.shlh.saas.util.FileUtils;
import com.shlh.saas.util.ExcelUtils;
import com.shlh.saas.util.ThreadPoolFactory;
import com.shlh.saas.util.PerformanceMonitor;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;


/**
 * 广交会展商控制器
 */
@RestController
@RequestMapping("/exhibitors")
@Slf4j
public class CantonFairExhibitorController {

    @Autowired
    private CantonFairExhibitorService cantonFairExhibitorService;

    @Autowired
    private WorkbenchStatsService workbenchStatsService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private ExportRecordService exportRecordService;

    @Autowired
    private ThreadPoolFactory threadPoolFactory;

    @Autowired
    private PerformanceMonitor performanceMonitor;

    /**
     * 搜索广交会展商数据（带分页）- 多线程优化版本
     */
    @GetMapping("/canton-fair/search")
    public Result searchCantonFairExhibitors(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String product,      //产品名称
            @RequestParam(required = false) String sessionInfo,  // 广交会届数
            @RequestParam(required = false) String category,     // 产品类别
            @RequestParam(required = false) String companyType,  // 公司类型
            @RequestParam(required = false) String companyScale, // 公司规模
            @RequestParam(required = false) String hasContact,   // 联系方式
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        return performanceMonitor.monitor("searchCantonFairExhibitors", () -> {
            PerformanceMonitor.Timer searchTimer = PerformanceMonitor.startTimer("searchCantonFairExhibitors_total");

            log.info("搜索广交会展商，关键词: {}, 广交会届数: {}, 产品名称: {}, 产品类别: {}, 公司类型: {}, 公司规模: {}, 联系方式: {}, 页码: {}, 每页大小: {}",
                    keyword, sessionInfo, product, category, companyType, companyScale, hasContact, page, size);

            try {
                // 获取当前用户ID
                Long userId = UserContext.getUserId();
                int offset = (page - 1) * size;

                // 第一页不扣除额度，免费查看
                if (page == 1) {
                    return handleFirstPageSearchOptimized(userId, keyword, product, sessionInfo, category, companyType, companyScale, hasContact, offset, size, page, searchTimer);
                } else {
                    return handlePaidPageSearchOptimized(userId, keyword, product, sessionInfo, category, companyType, companyScale, hasContact, offset, size, page, searchTimer);
                }
            } catch (ExecutionException e) {
                searchTimer.stop();
                log.error("并发执行搜索任务失败", e.getCause());
                return Result.error("搜索数据失败: " + e.getCause().getMessage());
            } catch (Exception e) {
                searchTimer.stop();
                log.error("搜索广交会展商数据失败", e);
                return Result.error("搜索广交会展商数据失败: " + e.getMessage());
            }
        });
    }

    /**
     * 处理第一页搜索（免费）- 多线程优化
     */
    private Result handleFirstPageSearchOptimized(Long userId, String keyword, String product, String sessionInfo, String category,
                                                String companyType, String companyScale, String hasContact, int offset, int size, int page,
                                                PerformanceMonitor.Timer searchTimer)
            throws ExecutionException, InterruptedException {

        log.info("开始第一页搜索优化处理，用户ID: {}", userId);

        // 并发执行数据查询和总数统计
        Future<List<BaseCantonFairExhibitor>> exhibitorsFuture = threadPoolFactory.submitDataQuery(() -> {
            return performanceMonitor.monitorDbQuery("exhibitors_search_page1", () -> {
                log.debug("执行展商数据查询，offset: {}, size: {}", offset, size);
                try {
                    return cantonFairExhibitorService.searchByKeywordInAllFieldsWithFilters(
                        keyword, product, sessionInfo, category, companyType, companyScale, hasContact, offset, size);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        });

        Future<Long> totalFuture = threadPoolFactory.submitDataQuery(() -> {
            return performanceMonitor.monitorDbQuery("exhibitors_count_page1", () -> {
                log.debug("执行展商总数统计查询");
                return cantonFairExhibitorService.countByKeywordInAllFieldsWithFilters(
                    keyword, product, sessionInfo, category, companyType, companyScale, hasContact);
            });
        });

        // 异步更新搜索统计信息（非关键路径）
        CompletableFuture<Void> statsUpdateFuture = CompletableFuture.runAsync(() -> {
            performanceMonitor.monitor("update_search_stats_page1", () -> {
                log.debug("更新搜索统计信息，用户ID: {}", userId);
                workbenchStatsService.incrementCantonExhibitorSearchCount(userId);
            });
        }, threadPoolFactory.getDataProcessExecutor());

        // 等待关键数据查询结果
        List<BaseCantonFairExhibitor> exhibitors = exhibitorsFuture.get();
        long total = totalFuture.get();

        log.info("第一页查询完成，展商数据: {} 条，总数: {}，耗时: {}ms",
                exhibitors.size(), total, searchTimer.stop());

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", exhibitors);
        result.put("total", total);
        result.put("size", size);
        result.put("current", page);

        // 记录线程池状态（调试用）
        if (log.isDebugEnabled()) {
            log.debug("第一页搜索完成，线程池状态: {}", threadPoolFactory.getPoolMonitorInfo());
        }

        return Result.success(result);
    }

    /**
     * 处理付费页面搜索 - 多线程优化
     */
    private Result handlePaidPageSearchOptimized(Long userId, String keyword, String product, String sessionInfo, String category,
                                                String companyType, String companyScale, String hasContact, int offset, int size, int page,
                                                PerformanceMonitor.Timer searchTimer)
            throws ExecutionException, InterruptedException {

        log.info("开始付费页面搜索优化处理，用户ID: {}, 页码: {}", userId, page);

        // 并发检查用户余额
        Future<UserBalance> userBalanceFuture = threadPoolFactory.submitDataQuery(() -> {
            return performanceMonitor.monitorDbQuery("user_balance_check_paid", () -> {
                log.debug("检查用户余额，用户ID: {}", userId);
                return userBalanceService.getByUserId(userId);
            });
        });

        // 先检查余额
        UserBalance userBalance = userBalanceFuture.get();
        if (userBalance == null || userBalance.getViewRecordsRemaining() < size) {
            searchTimer.stop();
            log.warn("用户余额不足，用户ID: {}, 剩余额度: {}, 需要额度: {}",
                    userId, userBalance != null ? userBalance.getViewRecordsRemaining() : 0, size);
            return Result.error("您的查看记录余额不足，请充值后再查看");
        }

        // 并发执行数据查询和总数统计
        Future<List<BaseCantonFairExhibitor>> exhibitorsFuture = threadPoolFactory.submitDataQuery(() -> {
            return performanceMonitor.monitorDbQuery("exhibitors_search_paid", () -> {
                log.debug("执行付费页面展商数据查询，offset: {}, size: {}", offset, size);
                try {
                    return cantonFairExhibitorService.searchByKeywordInAllFieldsWithFilters(
                        keyword, product, sessionInfo, category, companyType, companyScale, hasContact, offset, size);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        });

        Future<Long> totalFuture = threadPoolFactory.submitDataQuery(() -> {
            return performanceMonitor.monitorDbQuery("exhibitors_count_paid", () -> {
                log.debug("执行付费页面展商总数统计查询");
                return cantonFairExhibitorService.countByKeywordInAllFieldsWithFilters(
                    keyword, product, sessionInfo, category, companyType, companyScale, hasContact);
            });
        });

        // 等待查询结果
        List<BaseCantonFairExhibitor> exhibitors = exhibitorsFuture.get();
        long total = totalFuture.get();

        // 异步扣除余额和更新统计（在后台执行，不阻塞响应）
        CompletableFuture<Void> balanceAndStatsUpdateFuture = CompletableFuture.runAsync(() -> {
            performanceMonitor.monitor("deduct_balance_and_stats_paid", () -> {
                log.debug("扣除用户余额和更新统计，用户ID: {}, 扣除数量: {}", userId, exhibitors.size());
                userBalanceService.deductViewRecords(userId, exhibitors.size());
                workbenchStatsService.incrementCantonExhibitorSearchCount(userId);
            });
        }, threadPoolFactory.getDataProcessExecutor());

        log.info("付费页面查询完成，展商数据: {} 条，总数: {}，扣除余额: {}，耗时: {}ms",
                exhibitors.size(), total, exhibitors.size(), searchTimer.stop());

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", exhibitors);
        result.put("total", total);
        result.put("size", size);
        result.put("current", page);

        // 记录线程池状态（调试用）
        if (log.isDebugEnabled()) {
            log.debug("付费页面搜索完成，线程池状态: {}", threadPoolFactory.getPoolMonitorInfo());
        }

        return Result.success(result);
    }

    /**
     * 获取符合条件的记录总数
     */
    @PostMapping("/canton-fair/count")
    public Result getCantonFairExhibitorsCount(@RequestBody Map<String, Object> params) {
        String keyword = params != null && params.containsKey("keyword") ? (String) params.get("keyword") : null;
        String product = params != null && params.containsKey("product") ? (String) params.get("product") : null;
        String sessionInfo = params != null && params.containsKey("sessionInfo") ? (String) params.get("sessionInfo") : null;
        String companyType = params != null && params.containsKey("companyType") ? (String) params.get("companyType") : null;
        String companyScale = params != null && params.containsKey("companyScale") ? (String) params.get("companyScale") : null;
        String hasContact = params != null && params.containsKey("hasContact") ? (String) params.get("hasContact") : null;
        String category = null;  // 因为前端目前没有传递category参数，这里设为null

        log.info("获取广交会展商数据总数，关键词：{}, 届数：{}, 公司类型：{}, 公司规模：{}",
                keyword, sessionInfo, companyType, companyScale);

        try {
            long count;
            if (sessionInfo != null || companyType != null || companyScale != null || hasContact != null) {
                // 使用带有筛选条件的方法
                count = cantonFairExhibitorService.countByKeywordInAllFieldsWithFilters(
                        keyword, product, sessionInfo, category, companyType, companyScale, hasContact);
            } else {
                // 使用原来的方法
                count = cantonFairExhibitorService.countByKeywordInAllFields(keyword);
            }

            // 限制最大返回数量为100万
            if (count > 1000000) {
                count = 1000000;
            }

            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取广交会展商数据总数失败", e);
            return Result.error("获取广交会展商数据总数失败: " + e.getMessage());
        }
    }

    /**
     * 导出广交会展商数据 - 多线程优化版本
     */
    @PostMapping("/canton-fair/export")
    public void exportCantonFairExhibitors(
            HttpServletResponse response,
            @RequestBody(required = false) Map<String, Object> params,
            @RequestParam(required = true) Integer exportCount,
            @RequestParam(required = false) String selectedFields,
            @RequestParam(required = false, defaultValue = "zh") String language) {

        PerformanceMonitor.Timer exportTimer = PerformanceMonitor.startTimer("exportCantonFairExhibitors_total");

        log.info("导出广交会展商数据，参数: {}, 导出数量: {}, 选中字段: {}, 语言: {}", params, exportCount, selectedFields, language);

        try {
            Long userId = UserContext.getUserId();

            // 并发执行用户余额检查和参数处理
            Future<UserBalance> userBalanceFuture = threadPoolFactory.submitDataQuery(() -> {
                return performanceMonitor.monitorDbQuery("export_user_balance_check", () -> {
                    log.debug("检查导出用户余额，用户ID: {}", userId);
                    return userBalanceService.getByUserId(userId);
                });
            });

            // 并发处理参数提取
            Future<Map<String, String>> paramsFuture = threadPoolFactory.submitDataProcess(() -> {
                return performanceMonitor.monitorDataProcess("extract_export_params", () -> {
                    log.debug("提取导出参数");
                    Map<String, String> extractedParams = new HashMap<>();
                    extractedParams.put("keyword", params != null && params.containsKey("keyword") ? (String) params.get("keyword") : null);
                    extractedParams.put("product", params != null && params.containsKey("product") ? (String) params.get("product") : null);
                    extractedParams.put("sessionInfo", params != null && params.containsKey("sessionInfo") ? (String) params.get("sessionInfo") : null);
                    extractedParams.put("companyType", params != null && params.containsKey("companyType") ? (String) params.get("companyType") : null);
                    extractedParams.put("companyScale", params != null && params.containsKey("companyScale") ? (String) params.get("companyScale") : null);
                    extractedParams.put("hasContact", params != null && params.containsKey("hasContact") ? (String) params.get("hasContact") : null);
                    return extractedParams;
                });
            });

            // 等待用户余额检查结果
            UserBalance userBalance = userBalanceFuture.get();
            if (userBalance == null || userBalance.getExportQuotaRemaining() < exportCount) {
                exportTimer.stop();
                log.warn("用户导出余额不足，用户ID: {}, 剩余额度: {}, 需要额度: {}",
                        userId, userBalance != null ? userBalance.getExportQuotaRemaining() : 0, exportCount);
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"您的导出次数余额不足，请充值后再导出\"}");
                return;
            }

            // 限制最大导出数量为100万
            if (exportCount > 1000000) {
                exportCount = 1000000;
                log.info("导出数量超过限制，调整为: {}", exportCount);
            }

            // 获取参数处理结果
            Map<String, String> extractedParams = paramsFuture.get();
            String keyword = extractedParams.get("keyword");
            String product = extractedParams.get("product");
            String sessionInfo = extractedParams.get("sessionInfo");
            String companyType = extractedParams.get("companyType");
            String companyScale = extractedParams.get("companyScale");
            String hasContact = extractedParams.get("hasContact");
            String category = null;  // 因为前端目前没有传递category参数，这里设为null

            log.info("导出筛选条件：关键词={}, 届数={}, 公司类型={}, 公司规模={}, 联系方式={}", keyword, sessionInfo, companyType, companyScale, hasContact);

            // 并发查询数据
            final Integer finalExportCount = exportCount;
            Future<List<BaseCantonFairExhibitor>> exhibitorsFuture = threadPoolFactory.submitDataQuery(() -> {
                return performanceMonitor.monitorDbQuery("export_exhibitors_query", () -> {
                    log.debug("开始查询导出数据，数量: {}", finalExportCount);
                    if (sessionInfo != null || companyType != null || companyScale != null || hasContact != null) {
                        // 使用带有筛选条件的导出专用方法
                        log.info("使用筛选条件查询导出数据（导出专用，不脱敏）");
                        try {
                            return cantonFairExhibitorService.searchByKeywordInAllFieldsWithFiltersForExport(
                                    keyword, product, sessionInfo, category, companyType, companyScale, hasContact, 0, finalExportCount);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(e);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        // 使用导出专用方法
                        log.info("不使用筛选条件查询导出数据（导出专用，不脱敏）");
                        return cantonFairExhibitorService.searchByKeywordInAllFieldsForExport(keyword, product, 0, finalExportCount);
                    }
                });
            });

            // 等待数据查询结果
            List<BaseCantonFairExhibitor> exhibitors = exhibitorsFuture.get();

            log.info("查询到符合条件的展商数据: {} 条", exhibitors.size());

            if (exhibitors.isEmpty()) {
                exportTimer.stop();
                log.warn("没有找到符合条件的数据");
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"没有找到符合条件的数据\"}");
                return;
            }

            // 并发处理字段映射和余额扣除
            Future<Map<String, Object>> fieldProcessingFuture = threadPoolFactory.submitDataProcess(() -> {
                return performanceMonitor.monitorDataProcess("field_processing", () -> {
                    log.debug("开始处理字段映射，语言: {}", language);
                    Map<String, String> fieldMapping = createFieldMapping(language);
                    String[] selectedFieldArray;
                    String[] selectedColumnNames;

                    if (selectedFields != null && !selectedFields.trim().isEmpty()) {
                        // 解析选中的字段
                        String[] requestedFields = selectedFields.split(",");
                        List<String> validFields = new ArrayList<>();
                        List<String> validColumnNames = new ArrayList<>();

                        for (String field : requestedFields) {
                            field = field.trim();
                            if (fieldMapping.containsKey(field)) {
                                validFields.add(field);
                                validColumnNames.add(fieldMapping.get(field));
                            } else {
                                log.warn("无效的字段名: {}", field);
                            }
                        }

                        if (validFields.isEmpty()) {
                            throw new RuntimeException("没有有效的字段被选中，请至少选择一个有效字段");
                        }

                        selectedFieldArray = validFields.toArray(new String[0]);
                        selectedColumnNames = validColumnNames.toArray(new String[0]);
                        log.info("有效字段数量: {}, 字段列表: {}", validFields.size(), validFields);
                    } else {
                        // 如果没有指定字段，使用默认字段
                        selectedFieldArray = getDefaultFields();
                        selectedColumnNames = getDefaultColumnNames(language);
                        log.info("使用默认字段进行导出");
                    }

                    // 自动确定标红字段（重要字段）
                    String[] highlightFieldArray = getHighlightFields(selectedFieldArray);
                    log.info("自动标红字段数量: {}, 标红字段列表: {}", highlightFieldArray.length, Arrays.toString(highlightFieldArray));

                    Map<String, Object> result = new HashMap<>();
                    result.put("selectedFieldArray", selectedFieldArray);
                    result.put("selectedColumnNames", selectedColumnNames);
                    result.put("highlightFieldArray", highlightFieldArray);
                    return result;
                });
            });

            // 异步扣除余额和更新统计
            CompletableFuture<Void> balanceUpdateFuture = CompletableFuture.runAsync(() -> {
                performanceMonitor.monitor("balance_and_stats_update", () -> {
                    log.debug("扣除用户导出余额和更新统计，用户ID: {}, 扣除数量: {}", userId, exhibitors.size());
                    userBalanceService.deductExportQuota(userId, exhibitors.size());
                    workbenchStatsService.incrementCantonExhibitorExportCount(userId, exhibitors.size());
                    log.info("已扣除用户导出次数: {}", exhibitors.size());
                });
            }, threadPoolFactory.getDataProcessExecutor());

            // 等待字段处理结果
            Map<String, Object> fieldResult = fieldProcessingFuture.get();
            String[] selectedFieldArray = (String[]) fieldResult.get("selectedFieldArray");
            String[] selectedColumnNames = (String[]) fieldResult.get("selectedColumnNames");
            String[] highlightFieldArray = (String[]) fieldResult.get("highlightFieldArray");

            // 设置导出文件名（支持国际化）
            String fileNamePrefix = "en".equals(language) ? "Canton_Fair_Exhibitors_Data" : "广交会展商数据";
            String fileName = fileNamePrefix + "_" + System.currentTimeMillis() + ".xlsx";

            // 并发处理文件信息和导出记录
            Future<Void> recordFuture = threadPoolFactory.submitDataProcess(() -> {
                return performanceMonitor.monitorDataProcess("export_record_processing", () -> {
                    log.debug("处理导出记录，用户ID: {}, 文件名: {}", userId, fileName);
                    // 获取当前时间戳作为文件名一部分
                    String filePath = "/export/" + fileName;

                    // 计算文件大小（以KB为单位）
                    String fileSize = FileUtils.estimateExcelSize(exhibitors.size()) + "KB";

                    // 保存导出记录
                    exportRecordService.addExportRecord(
                            userId,
                            fileName,
                            "canton-fair-exhibitors", // 数据来源
                            fileSize,
                            exhibitors.size(),
                            filePath
                    );
                    return null;
                });
            });

            // 等待余额更新完成
            balanceUpdateFuture.get();

            // 执行Excel导出（使用动态字段和自动标红样式）
            performanceMonitor.monitorExport("excel_generation", () -> {
                log.debug("开始生成Excel文件，数据量: {}", exhibitors.size());
                try {
                    // 设置响应头，防止连接中断
                    response.setHeader("Connection", "Keep-Alive");
                    response.setHeader("Keep-Alive", "timeout=600");
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

                    // 根据数据量选择不同的导出方法
                    if (exhibitors.size() > 10000) {
                        log.info("数据量超过10000条，使用优化的导出方法");
                        ExcelUtils.exportExcelWithHighlightOptimized(response, exhibitors, "广交会展商数据",
                                selectedColumnNames, selectedFieldArray, highlightFieldArray);
                    } else {
                        log.info("数据量不超过10000条，使用标准导出方法");
                        ExcelUtils.exportExcelWithHighlight(response, exhibitors, "广交会展商数据",
                                selectedColumnNames, selectedFieldArray, highlightFieldArray);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return null;
            });

            // 等待导出记录保存完成
            recordFuture.get();

            long totalTime = exportTimer.stopAndLog();
            log.info("成功导出广交会展商数据，包含字段: {}，自动标红字段: {}，总耗时: {}ms",
                    Arrays.toString(selectedColumnNames), Arrays.toString(highlightFieldArray), totalTime);

            // 记录性能统计
            if (log.isDebugEnabled()) {
                log.debug("导出完成，线程池状态: {}", threadPoolFactory.getPoolMonitorInfo());
                log.debug("性能报告: {}", performanceMonitor.getMethodStats("exportCantonFairExhibitors"));
            }

        } catch (ExecutionException e) {
            exportTimer.stop();
            log.error("并发执行导出任务失败", e.getCause());
            try {
                // 检查response是否已经提交
                if (!response.isCommitted()) {
                    response.reset();
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("{\"message\":\"导出数据失败: " + e.getCause().getMessage().replace("\"", "'") + "\"}");
                } else {
                    log.warn("响应已经提交，无法发送错误信息");
                }
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        } catch (Exception e) {
            exportTimer.stop();
            log.error("导出广交会展商数据失败", e);
            try {
                // 检查response是否已经提交
                if (!response.isCommitted()) {
                    response.reset();
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("{\"message\":\"导出数据失败: " + e.getMessage().replace("\"", "'") + "\"}");
                } else {
                    log.warn("响应已经提交，无法发送错误信息");
                }
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 获取性能监控信息
     */
    @GetMapping("/performance/monitor")
    public Result getPerformanceMonitor() {
        try {
            log.info("获取广交会展商控制器性能监控信息");
            Map<String, Object> monitorInfo = new HashMap<>();
            monitorInfo.put("threadPoolStatus", threadPoolFactory.getPoolMonitorInfo());
            monitorInfo.put("performanceReport", performanceMonitor.getPerformanceReport());
            monitorInfo.put("performanceWarnings", performanceMonitor.getPerformanceWarnings(1000)); // 超过1秒的操作

            return Result.success(monitorInfo);
        } catch (Exception e) {
            log.error("获取性能监控信息失败", e);
            return Result.error("获取性能监控信息失败: " + e.getMessage());
        }
    }

    /**
     * 清除性能统计数据
     */
    @PostMapping("/performance/clear")
    public Result clearPerformanceStats() {
        try {
            log.info("清除广交会展商控制器性能统计数据");
            performanceMonitor.clearStats();
            return Result.success("性能统计数据已清除");
        } catch (Exception e) {
            log.error("清除性能统计数据失败", e);
            return Result.error("清除性能统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取线程池详细状态
     */
    @GetMapping("/performance/threadpool")
    public Result getThreadPoolStatus() {
        try {
            log.info("获取线程池详细状态信息");
            Map<String, Object> threadPoolInfo = new HashMap<>();
            threadPoolInfo.put("dataQueryExecutor", getExecutorInfo(threadPoolFactory.getDataQueryExecutor()));
            threadPoolInfo.put("dataProcessExecutor", getExecutorInfo(threadPoolFactory.getDataProcessExecutor()));
            threadPoolInfo.put("exportExecutor", getExecutorInfo(threadPoolFactory.getExportExecutor()));

            return Result.success(threadPoolInfo);
        } catch (Exception e) {
            log.error("获取线程池状态失败", e);
            return Result.error("获取线程池状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取线程池执行器信息
     */
    private Map<String, Object> getExecutorInfo(java.util.concurrent.ThreadPoolExecutor executor) {
        Map<String, Object> info = new HashMap<>();
        info.put("corePoolSize", executor.getCorePoolSize());
        info.put("maximumPoolSize", executor.getMaximumPoolSize());
        info.put("activeCount", executor.getActiveCount());
        info.put("queueSize", executor.getQueue().size());
        info.put("completedTaskCount", executor.getCompletedTaskCount());
        info.put("taskCount", executor.getTaskCount());
        info.put("isShutdown", executor.isShutdown());
        info.put("isTerminated", executor.isTerminated());
        return info;
    }

    /**
     * 查找准确联系信息
     */
    @GetMapping("/canton-fair/contact")
    public Result getExhibitorFullContactInfo(@RequestParam(required = true) Long exhibitorId, 
                                             @RequestParam(required = true) Integer sessionNumber,
                                             @RequestParam(required = true) String fieldName) {
        try {
            // 获取当前用户信息
            Long userId = UserContext.getUserId();
            log.info("{} 正在查找准确联系信息，展商ID: {}, 届数: {}, 字段名: {}", userId,exhibitorId, sessionNumber, fieldName);
            
            // 检查用户是否有权限查看完整联系信息
            // 查询用户额度
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getViewRecordsRemaining() < 1) {
                return Result.error("您的查看记录余额不足，请充值后再查看");
            }
            
            // 获取完整联系信息
            String contactInfo = cantonFairExhibitorService.getFullContactInfo(exhibitorId, sessionNumber, fieldName);
            
            // 记录用户查看详情的操作
            // 增加广交会展商搜索次数统计
            workbenchStatsService.incrementCantonExhibitorSearchCount(userId);

            // 扣除用户查看记录余额
            userBalanceService.deductViewRecords(userId, 1);
            
            // 创建返回数据结构，与前端期望的格式匹配
            Map<String, String> resultData = new HashMap<>();
            resultData.put(fieldName, contactInfo);
            
            return Result.success(resultData);
        } catch (Exception e) {
            return Result.error("获取联系信息失败：" + e.getMessage());
        }
    }

    /**
     * 创建字段映射关系（支持国际化）
     * @param language 语言代码（zh/en）
     * @return 字段名到对应语言标题的映射
     */
    private Map<String, String> createFieldMapping(String language) {
        Map<String, String> fieldMapping = new HashMap<>();
        boolean isEnglish = "en".equals(language);

        // 直接属性字段
        fieldMapping.put("companyName", isEnglish ? "Company Name" : "公司名称");
        fieldMapping.put("boothNumber", isEnglish ? "Booth Number" : "展位号");
        fieldMapping.put("contactPerson", isEnglish ? "Contact Person" : "联系人");

        fieldMapping.put("address", isEnglish ? "Address" : "地址");
        fieldMapping.put("postalCode", isEnglish ? "Postal Code" : "邮编");
        fieldMapping.put("city", isEnglish ? "City" : "城市");
        fieldMapping.put("province", isEnglish ? "Province" : "省份");
        fieldMapping.put("category", isEnglish ? "Industry" : "行业");
        fieldMapping.put("establishmentYear", isEnglish ? "Establishment Year" : "成立年份");

        // extendedFields中的字段，使用点号访问
        fieldMapping.put("extendedFields.sessionInfo", isEnglish ? "Session" : "届次");
        fieldMapping.put("extendedFields.mainProducts", isEnglish ? "Main Products" : "主要产品");
        fieldMapping.put("extendedFields.mobilePhone", isEnglish ? "Mobile Phone" : "手机号码");
        fieldMapping.put("extendedFields.phone", isEnglish ? "Phone" : "固定电话");
        fieldMapping.put("extendedFields.fax", isEnglish ? "Fax" : "传真");
        fieldMapping.put("extendedFields.email", isEnglish ? "Email" : "邮箱");
        fieldMapping.put("extendedFields.website", isEnglish ? "Website" : "网站");
        fieldMapping.put("extendedFields.companyType", isEnglish ? "Company Type" : "公司类型");
        fieldMapping.put("extendedFields.companyScale", isEnglish ? "Company Size" : "公司规模");
        fieldMapping.put("extendedFields.recentExhibitionHistory", isEnglish ? "Recent Exhibition History" : "历史参展");
        fieldMapping.put("extendedFields.registeredCapital", isEnglish ? "Registered Capital" : "注册资金");
        fieldMapping.put("extendedFields.companyProfile", isEnglish ? "Company Profile" : "公司简介");
        return fieldMapping;
    }

    /**
     * 获取默认字段列表
     * @return 默认字段数组
     */
    private String[] getDefaultFields() {
        return new String[]{
            "companyName", "boothNumber", "contactPerson", "website",
            "address", "postalCode", "extendedFields.sessionInfo", "extendedFields.mainProducts",
            "extendedFields.mobilePhone", "extendedFields.phone", "extendedFields.fax", "extendedFields.email"
        };
    }

    /**
     * 获取默认列名列表（支持国际化）
     * @param language 语言代码（zh/en）
     * @return 默认列名数组
     */
    private String[] getDefaultColumnNames(String language) {
        boolean isEnglish = "en".equals(language);
        if (isEnglish) {
            return new String[]{
                "Company Name", "Booth Number", "Contact Person", "Website",
                "Address", "Postal Code", "Session", "Main Products",
                "Mobile Phone", "Phone", "Fax", "Email"
            };
        } else {
            return new String[]{
                "公司名称", "展位号", "联系人", "网站",
                "地址", "邮编", "届次", "主要产品",
                "手机号码", "固定电话", "传真", "邮箱"
            };
        }
    }

    /**
     * 获取需要标红的重要字段列表
     * @param selectedFields 用户选中的字段列表
     * @return 需要标红的字段数组（只包含用户选中的重要字段）
     */
    private String[] getHighlightFields(String[] selectedFields) {
        // 定义重要字段列表（需要标红的字段）
        String[] importantFields = {
            "companyName",                    // 公司名称
            "contactPerson",                  // 联系人
            "website",                        // 网站
            "extendedFields.mobilePhone",     // 手机号码
            "extendedFields.phone",           // 固定电话
            "extendedFields.email"            // 邮箱
        };

        List<String> highlightFields = new ArrayList<>();
        Set<String> selectedFieldSet = new HashSet<>(Arrays.asList(selectedFields));

        // 只有当重要字段被用户选中时，才加入标红列表
        for (String importantField : importantFields) {
            if (selectedFieldSet.contains(importantField)) {
                highlightFields.add(importantField);
            }
        }

        return highlightFields.toArray(new String[0]);
    }

}